﻿using Domain;
using Domain.Entity;
using Domain.Repository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys
{
	public class UserRolesRepository : IUserRolesRepository
	{
		private readonly MyDbContext myDbContext;

		public UserRolesRepository(MyDbContext myDbContext)
		{
			this.myDbContext = myDbContext;
		}

		public Task<List<UserRoleInfo>> GetUsersWithRolesAsync()
		{
			return null;
		}

		public async Task<UserRoles> SelectUserRolesById(int id)
		{
			return await myDbContext.UserRolesSelect.Where(e => e.UserID == id).FirstOrDefaultAsync();
		}

		public async Task<bool> UserRolesAdd(UserRoles userRoles)
		{
			myDbContext.UserRolesSelect.Add(userRoles);
			return await myDbContext.SaveChangesAsync() > 0;
		}

		public async Task<bool> UserRolesDelete(int id)
		{
			UserRoles userRoles = new UserRoles
			{
				UserRolesID = id
			};
			myDbContext.UserRolesSelect.Remove(userRoles);
			return await myDbContext.SaveChangesAsync() > 0;
		}

		public UserRolesFenYe UserRolesFenYe(int page, int pageSize)
		{
			var query = myDbContext.UserRolesSelect.AsQueryable();
			int totalRecords = query.Count();
			var UR = (from ur in myDbContext.UserRolesSelect // 从 UserRoles 表获取  
					  join u in myDbContext.User on ur.UserID equals u.UId // 用户表连接  
					  join r in myDbContext.Roles on ur.RolesID equals r.RolesID // 角色表连接，注意属性名可能需要根据实际情况调整  
					  select new UserRoleInfo
					  {
						  UId = u.UId,
						  UName = u.UName,
						  UTrueName = u.UTrueName,
						  UPassWord = u.UPassWord,
						  RolesName = r.RolesName,
						  RolesID = r.RolesID
					  }).Skip((page - 1) * pageSize).Take(pageSize);
			var infos = UR.ToList();
			return new UserRolesFenYe
			{
				totalRecords = totalRecords,
				infos = infos
			};
		}

		public async Task<bool> UserRolesUpdate(UserRoles userRoles)
		{
			myDbContext.UserRolesSelect.Update(userRoles);
			return await myDbContext.SaveChangesAsync() > 0;
		}
	}
}
